package com.ejlchina.tool.fragment

import android.annotation.SuppressLint
import android.graphics.Paint
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.os.bundleOf
import androidx.core.widget.doAfterTextChanged
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.GridLayoutManager
import com.adolf.androiddemo.R
import com.adolf.androiddemo.databinding.FragmentTemperatureAlarmBinding
import com.huyuhui.fastble.data.BleDevice
import com.ejlchina.tool.MainActivity
import com.ejlchina.tool.adapter.DeviceAdapterRadio
import com.ejlchina.tool.base.BaseBindingFragment2
import com.ejlchina.tool.bean.BleDeviceBean
import com.ejlchina.tool.bean.TemperatureAlarmBean
import com.ejlchina.tool.constant.REQUEST_FAN_CONTROL_KEY
import com.ejlchina.tool.enums.FanControlEnum
import com.ejlchina.tool.enums.SuccessFailEnum
import com.ejlchina.tool.singleton.GlobalConnectObject
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_GET_DOWNWARD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_GET_UPWARD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_SET_DOWNLOAD
import com.ejlchina.tool.util.COMMAND_TEMPERATURE_ALARM_SET_UPWARD
import com.ejlchina.tool.util.LOG_TAG
import com.ejlchina.tool.util.bytearray.toHexString
import com.ejlchina.tool.util.showToast
import com.ejlchina.tool.view.GridItemDecoration

const val BUNDLE_FAN_CONTROL_MODE = "BUNDLE_FAN_CONTROL_MODE"
const val BUNDLE_FAN_CONTROL_SELECT_INDEX = "BUNDLE_FAN_CONTROL_SELECT_INDEX"
const val BUNDLE_FAN_CONTROL_TEMPERATURE = "BUNDLE_FAN_CONTROL_TEMPERATURE"
class TemperatureAlarmFragment: BaseBindingFragment2<FragmentTemperatureAlarmBinding>() {


    private val temperatureAlarmBeanRead = TemperatureAlarmBean()
    private var isBackFromFan = false
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews()
        initData()
    }

    private fun initViews(){
        setHeadTitle("温度警报")
        setRightIconVisibility(View.GONE)
        initListeners()
    }

    private fun initListeners(){
        binding.btnConfirm.setOnClickListener {
            setTemperatureAlarmData(deviceAdapter.getSelectDevice())
        }

        binding.etHighTemperature.doAfterTextChanged { editable ->
            editable?.let {
                val text = it.toString()
                if (!invalidateInput(text)){
                    temperatureAlarmBeanRead.highTemperature = text.toInt()
                }
            }
        }

        binding.etLowTemperature.doAfterTextChanged { editable ->
            editable?.let {
                val text = it.toString()
                if (!invalidateInput(text)){
                    temperatureAlarmBeanRead.lowTemperature = text.toInt()
                }
            }
        }

        binding.includeFan.tvOff.setOnClickListener {
            setFanControlMode(FanControlEnum.OFF)
            temperatureAlarmBeanRead.fanControl = FanControlEnum.OFF
        }
        binding.includeFan.tvControlByTemperature.setOnClickListener {
            setFanControlMode(FanControlEnum.TEMPERATURE_CONTROL)
            temperatureAlarmBeanRead.fanControl = FanControlEnum.TEMPERATURE_CONTROL
        }

        binding.includeFan.tvOn.setOnClickListener {
            setFanControlMode(FanControlEnum.ON)
            temperatureAlarmBeanRead.fanControl = FanControlEnum.ON
        }

        binding.etFanOnTemperature.doAfterTextChanged { editable ->
            editable?.let {
                val text = it.toString()
                if (!invalidateInput(text)){
                    temperatureAlarmBeanRead.fanControlTemperature = text.toInt()
                }
            }
        }
    }

    private fun invalidateInput(text: String): Boolean{
        return text.isEmpty() || text == "+" || text == "-"
    }

    private fun initData(){
        initDevices()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun initDevices() {
        deviceAdapter = DeviceAdapterRadio(GlobalConnectObject.getCurrentConnectDeviceList()){
            getTemperatureAlarmData(it)
        }
        binding.rvDevices.apply {
            adapter = deviceAdapter
            layoutManager = GridLayoutManager(requireContext(), 3)
            if (itemDecorationCount == 0) {
                addItemDecoration(GridItemDecoration(3, 11, 11))
            }
        }
    }

    override fun whenReceiveCommand(bleDevice: BleDeviceBean, command: String, commandByteArray: ByteArray) {
        super.whenReceiveCommand(bleDevice,command, commandByteArray)
        when(command){
            COMMAND_TEMPERATURE_ALARM_GET_UPWARD -> {
                setTemperatureAlarmBeanData(commandByteArray)
                setUIData()
            }
            COMMAND_TEMPERATURE_ALARM_SET_UPWARD -> {
                if (commandByteArray[4].toInt() == SuccessFailEnum.SUCCESS.value){
                    showToast("设置成功")
                } else {
                    showToast("设置失败")
                }
            }
        }
        dismissLoading()
    }

    private fun setTemperatureAlarmBeanData(byteArray: ByteArray) {
        temperatureAlarmBeanRead.fanControlTemperature = byteArray[3].toInt()
        temperatureAlarmBeanRead.fanControl = FanControlEnum.getFromValue(byteArray[2].toInt())
        temperatureAlarmBeanRead.lowTemperature = byteArray[1].toInt()
        temperatureAlarmBeanRead.highTemperature = byteArray[0].toInt()
        Log.i(LOG_TAG, "$temperatureAlarmBeanRead")

    }

    private fun setUIData(){
        binding.etHighTemperature.setText(temperatureAlarmBeanRead.highTemperature.toString())
        binding.etLowTemperature.setText(temperatureAlarmBeanRead.lowTemperature.toString())
        setFanControlMode(temperatureAlarmBeanRead.fanControl)
    }

    private fun getTemperatureAlarmData(bleDevice: BleDeviceBean){
        getCommandData(bleDevice, COMMAND_TEMPERATURE_ALARM_GET_DOWNWARD)
    }

    private fun setTemperatureAlarmData(bleDevice: BleDeviceBean){
        if (!checkInputData()) return
        setCommandData(bleDevice, COMMAND_TEMPERATURE_ALARM_SET_DOWNLOAD, getResultData())
    }

    private fun setFanControlMode(controlMode: FanControlEnum){
        val resUnselected = R.drawable.shape_co_10_so_f7f7f7
        val resSelected = R.drawable.shape_co_10_so_1f39ff_2
        val selectedTextColor = resources.getColor(R.color.white)
        val unselectedTextColor = resources.getColor(R.color.title_text_color)
        binding.includeFan.tvOff.setBackgroundResource(resUnselected)
        binding.includeFan.tvControlByTemperature.setBackgroundResource(resUnselected)
        binding.includeFan.tvOn.setBackgroundResource(resUnselected)
        binding.includeFan.tvOff.setTextColor(unselectedTextColor)
        binding.includeFan.tvControlByTemperature.setTextColor(unselectedTextColor)
        binding.includeFan.tvOn.setTextColor(unselectedTextColor)
        binding.layoutFanTemperature.visibility = View.GONE
        when(controlMode){
            FanControlEnum.OFF -> {
                binding.includeFan.tvOff.setBackgroundResource(resSelected)
                binding.includeFan.tvOff.setTextColor(selectedTextColor)
            }
            FanControlEnum.TEMPERATURE_CONTROL -> {
                binding.includeFan.tvControlByTemperature.setBackgroundResource(resSelected)
                binding.layoutFanTemperature.visibility = View.VISIBLE
                binding.etFanOnTemperature.setText(temperatureAlarmBeanRead.fanControlTemperature.toString())
                binding.includeFan.tvControlByTemperature.setTextColor(selectedTextColor)
            }
            FanControlEnum.ON -> {
                binding.includeFan.tvOn.setBackgroundResource(resSelected)
                binding.includeFan.tvOn.setTextColor(selectedTextColor)
            }
        }
    }

    //设置字体加粗
    private fun textBold(view: TextView, addBoldNum:Float) {
        view.apply {
            this.paint.style = Paint.Style.FILL_AND_STROKE
            this.paint.strokeWidth = addBoldNum
        }
        view.invalidate()
    }

    private fun checkInputData(): Boolean{
        if (invalidateInput(binding.etHighTemperature.text.toString())){
            showToast("请输入正确的高温阈值")
            return false
        }
        if (invalidateInput(binding.etLowTemperature.text.toString())){
            showToast("请输入正确的低温阈值")
            return false
        }

        if (temperatureAlarmBeanRead.fanControl == FanControlEnum.TEMPERATURE_CONTROL && invalidateInput(binding.etFanOnTemperature.text.toString())){
            showToast("请输入正确的风扇开启温度")
            return false
        }

        if (temperatureAlarmBeanRead.lowTemperature < -20 ||
            temperatureAlarmBeanRead.lowTemperature > 99 ||
            temperatureAlarmBeanRead.highTemperature < -20 ||
            temperatureAlarmBeanRead.highTemperature > 99 ||
            temperatureAlarmBeanRead.fanControlTemperature < -20 ||
            temperatureAlarmBeanRead.fanControlTemperature > 99){
            showToast("温度请设置在-20到99之间")
            return false
        }
        return true
    }

    private fun getResultData(): String{
        val byteArray = byteArrayOf(0,0,0,0)
        byteArray[3] = temperatureAlarmBeanRead.fanControlTemperature.toByte()
        byteArray[2] = temperatureAlarmBeanRead.fanControl.value.toByte()
        byteArray[1] = temperatureAlarmBeanRead.lowTemperature.toByte()
        byteArray[0] = temperatureAlarmBeanRead.highTemperature.toByte()
        return byteArray.toHexString(hasSpace = false)
    }
    override fun getViewBinding(inflater: LayoutInflater, container: ViewGroup): FragmentTemperatureAlarmBinding {
        return FragmentTemperatureAlarmBinding.inflate(inflater,container,true)
    }
}